/* Copyright (c) 2016-2020 Enfry Ltd. All Rights Reserved.
 * 
 * This software is the confidential and proprietary information of Enfry. 
 * You shall not disclose such Confidential Information
 * and shall use it only in accordance with the terms of the agreements
 * you entered into with Enfry.
 */
package com.enfry.common.util.json;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

/**
 * <请简单说明此类用途>
 * @Title com.enfry.common.util.json.JsonUtil
 * @author longguangxing
 * @date 2018年9月10日
 */
public class JsonUtil {

	public static List<Map<String, Object>> parseJSON2List(String jsonStr) {
		if(StringUtils.isEmpty(jsonStr)){
			return new ArrayList<>();
		}
		JSONArray jsonArr = JSONArray.parseArray(jsonStr);
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		Iterator<Object> it = jsonArr.listIterator();
		while (it.hasNext()) {
			JSONObject json2 = (JSONObject) it.next();
			list.add(parseJSON2Map(json2.toString()));
		}
		return list;
	}

	public static List<Object> parseToList(String jsonStr) {
		if(StringUtils.isEmpty(jsonStr)){
			return new ArrayList<>();
		}
		JSONArray jsonArr = JSONArray.parseArray(jsonStr);
		List<Object> list = new ArrayList<Object>();
		Iterator<Object> it = jsonArr.listIterator();
		while (it.hasNext()) {
			Object o = it.next();
			if (o instanceof JSONArray) {
				JSONArray json2 = (JSONArray) o;
				list.add(parseToList(json2.toString()));
			} else {
				JSONObject json2 = (JSONObject) o;
				list.add(parseJSON2Map(json2.toString()));
			}

		}
		return list;
	}

	/**
	 *
	 * @param jsonStr
	 * @return
	 */
	public static Map<String, Object> parseJSON2Map(String jsonStr) {

		Map<String, Object> map = new HashMap<String, Object>();
		if(StringUtils.isEmpty(jsonStr)){
			return map;
		}
		// 最外层解析
		JSONObject json = JSONObject.parseObject(jsonStr);
		for (Object k : json.keySet()) {
			Object v = json.get(k);
			// 如果内层还是数组的话，继续解析
			if (v instanceof JSONArray) {
				List<Object> list = new ArrayList<Object>();
				Iterator<Object> it = ((JSONArray) v).listIterator();
				while (it.hasNext()) {
					Object o = it.next();
					if (o instanceof JSONArray) {
						JSONArray json2 = (JSONArray) o;
						list.add(parseToList(json2.toString()));
					} else if (o instanceof JSONObject) {
						JSONObject json2 = (JSONObject) o;
						list.add(parseJSON2Map(json2.toString()));
					} else {
						list.add(o);
					}
				}
				map.put(k.toString(), list);
			} else if (v instanceof JSONObject) {
				JSONObject json2 = (JSONObject) v;
				map.put(k.toString(), parseJSON2Map(json2.toString()));
			} else {
				map.put(k.toString(), v);
			}
		}
		return map;
	}

	public static Map<String, Object> parseJSON2Map(JSONObject json) {
		return parseJSON2Map(json.toJSONString());
	}
}
